package optional;

import optional.entity.Student;
import org.junit.Test;

import java.util.Objects;
import java.util.Optional;

public class OptionTest {

    public Student createStu() {
        return new Student("haha", 20);
    }

    public Student createStu(String name, Integer age) {
        return new Student(name, age);
    }

    /**
     * 需要取出对象 加异常
     */
    @Test
    public void test01() {
        Student stu = createStu();
        Student student = Optional.ofNullable(stu).orElseThrow(IllegalArgumentException::new);
        System.out.println(stu);
        System.out.println(student.toString());
        System.out.println(student.getName());
    }

    /**
     * 对象不为空时直接操作
     */
    @Test
    public void test02() {
        Student stu = createStu();
        Optional.ofNullable(stu).ifPresent(System.out::println);
        System.out.println(stu);

    }

    /**
     * 对象为空是给一个默认对象（新对象）
     */
    @Test
    public void test03() {
        Student stu = null;
        Student student = Optional.ofNullable(stu).orElse(createStu("小徐", 23));
        System.out.println(stu);
        System.out.println(student);

    }

    /**
     * map 返回结果
     */
    @Test
    public void test04() {
        Student stu = createStu();
        String name = Optional.ofNullable(stu).map(Student::getName).orElseThrow(IllegalArgumentException::new);
        System.out.println("name: " + name);
    }

    /**
     * map 直接处理
     */
    @Test
    public void test05() {
        Student stu = createStu();
        Optional.ofNullable(stu).map(Student::getName).ifPresent(System.out::println);
    }

    /**
     * flatMap() 直接返回结果 对象所对应的属性必须被Optional包裹
     * eg :  private Optional<Integer> sex;
     *
     */
    /*@Test
    public void test06(){
        Student xxx = new Student("xxx", 20, Optional.of(20));
        Optional<Integer> integer = Optional.of(xxx).flatMap(Student::getSex);
        System.out.println("stu1: " + integer);
    }*/

    /**
     * fliter
     */
    @Test
    public void test07() {
        Student stu = createStu();
        Optional<Student> student = Optional.ofNullable(stu).filter(u -> u.getName() != null && !Objects.equals(u.getName(), ""));
        //需要获取出来 方法一
        Student x = student.isPresent() ? student.get() : null;
        //需要获取出来 方法二
        Student student1 = student.orElse(null);
        //判断处理
        Optional.ofNullable(student1).ifPresent(System.out::println);
        System.out.println(student1);
    }

    @Test
    public void t() {
        double base = 10000;
        double rate = 1.1;
        int year = 5;
        double v = 0;
        for (int i = 1; i <= year; i++) {
            if (i == 1) {
                v = base * rate;
            } else {
                v = (v + base) * rate;
            }
        }
        System.out.println(v);
        double v1 = v - year * base;
        System.out.println("xx: " + v1);
    }


}
